import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import useGlobalStore from '@/store/modules/global'
import commonRoutes from '@/router/route.common'
import asyncRoutes from '@/router/route.async'
import exceptionRoutes from '@/router/route.exception'

const routes: Array<RouteRecordRaw> = [
  // 无鉴权的业务路由 ex:登录
  ...commonRoutes,
  // 带鉴权的业务路由
  ...asyncRoutes,
  // 异常页必须放在路由匹配规则的最后
  ...exceptionRoutes
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 全局缓存
  const globalStore = useGlobalStore()
  globalStore.setNowRoute(to.path)
  if (!['/login', '/auth-login'].includes(to.path)) {
    // 全局缓存
    // const token = globalStore.token || localStorage.getItem('tokenMediaPlat')
    const token = globalStore.token
    if (!token) {
      if (import.meta.env.VITE_USER_NODE_ENV === 'development') {
        next({ path: '/login' })
      } else {
        window.open(`${import.meta.env.VITE_BASE_URL}${import.meta.env.VITE_UNIVERSE_LOGIN}`, '_self')
      }
    }
  }

  next()
  // 记录路由缓存
  let arrayCacheRoute = globalStore.arrayCacheRoute as any
  if (to.meta.cache && arrayCacheRoute.indexOf(to.name) === -1) {
    // 先把点击过的菜单存入
    arrayCacheRoute.push(to)
    // 再去重
    let find: any = []

    arrayCacheRoute.forEach((el: { path: any }) => {
      if (!find.find((e: { path: any }) => e.path == el.path)) {
        find.push(el)
      }
    })
    globalStore.setArrayCacheRoute(find)
  }
})

export default router
